<template>
  <div class="chat-container">
    <div class="chat-header">
      <button class="back-button" @click="goBack">返回</button>
      <h1>在线聊天</h1>
      <p class="username">用户: {{ username }}</p>
    </div>
    <div class="chat-main">
      <div class="friend-list">
        <h3>好友列表</h3>
        <ul>
          <li v-for="friend in friends" :key="friend" @click="selectFriend(friend)">
            {{ friend }}
          </li>
        </ul>
      </div>
      <div v-if="selectedFriend" class="chat-box">
        <div class="chat-content">
          <div class="message" v-for="(msg, index) in messages" :key="index">
            <!-- 如果是分隔线 -->
            <div v-if="msg.isDivider" class="divider-line">
              {{ msg.text }}
            </div>
            <!-- 如果是普通消息 -->
            <div v-else :class="['message-container', msg.isUser ? 'user-message-container' : 'other-message-container']">
              <div :class="['message-bubble', msg.isUser ? 'user-message' : 'other-message']">
                {{ msg.text }}
              </div>
            </div>
          </div>
        </div>
        <div class="chat-input">
          <input type="text" v-model="newMessage" placeholder="输入消息..." />
          <button @click="sendMessage">发送</button>
        </div>
      </div>
      <div v-else class="select-friend-hint">
        <p>请点击左侧好友开始聊天</p>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: localStorage.getItem('username')?.trim() || '匿名用户',
      newMessage: '',
      messages: [],
      friends: [],
      selectedFriend: null,
      ws: null,
      requestTypeMap: {}
    };
  },
  mounted() {
    this.connectWebSocket();
  },
  methods: {
    connectWebSocket() {
      console.log('尝试建立WebSocket连接...');
      this.ws = new WebSocket('ws://localhost:8080/lzl_content2_war_exploded/chat');
      
      this.ws.onopen = () => {
        console.log('WebSocket连接已建立');
        this.getFriends();
      };
      
      this.ws.onmessage = (event) => {
        console.log('收到服务器消息:', event.data);
        this.handleMessage(event.data);
      };
      
      this.ws.onclose = (event) => {
        console.log('WebSocket连接已关闭, 代码:', event.code, '原因:', event.reason);
      };
      
      this.ws.onerror = (error) => {
        console.error('WebSocket错误:', error);
      };
    },
    getFriends() {
      console.log('请求好友列表...');
      this.sendMessageToServer({ type: 1, username: this.username });
    },
    selectFriend(friend) {
      this.selectedFriend = friend;
      this.messages = [];
      console.log('加载与', friend, '的历史消息...');
      this.loadHistoricalMessages(friend);
    },
    loadHistoricalMessages(friend) {
      this.sendMessageToServer({ type: 2, sendmessage: this.username, receivemessage: friend });
    },
    sendMessage() {
      const messageContent = this.newMessage.trim();
      
      if (messageContent && this.selectedFriend) {
        console.log('用户输入的消息:', messageContent);
        
        this.messages.push({ text: messageContent, isUser: true });
        
        this.newMessage = '';
        
        console.log('发送消息到服务器...');
        this.sendMessageToServer({
          type: 5,
          sendmessage: this.username,
          receivemessage: this.selectedFriend,
          content: messageContent
        });
      } else {
        console.log('未输入消息或未选择好友');
      }
    },
    sendMessageToServer(message) {
      console.log('发送消息到服务器:', message);
      if (this.ws && this.ws.readyState === WebSocket.OPEN) {
        this.requestTypeMap[message.type] = message.type;
        this.ws.send(JSON.stringify(message));
      } else {
        console.error('无法发送消息，WebSocket连接未建立或已关闭');
      }
    },
    handleMessage(data) {
      try {
        const message = JSON.parse(data);
        console.log('处理服务器消息:', message);
        console.log('请求类型', message.type);
        switch (message.type) {
          case 1: // 好友列表
            if (message.friends) {
              this.friends = message.friends;
              console.log('收到好友列表:', this.friends);
            } else {
              console.error('未收到好友列表数据');
            }
            break;
          case 2: // 历史消息
            if (message.messages) {
              console.log('收到的历史消息数据:', message.messages); // 打印历史消息数据
              this.messages = message.messages.map(msg => ({
                text: msg.message,
                isUser: msg.sendMessage === this.username // 确保正确判断
              }));
              
              // 添加分隔线
              this.messages.push({
                text: '——————以上是历史消息——————',
                isDivider: true
              });
              
              console.log('处理后的消息数组:', this.messages);
            } else {
              console.error('未收到历史消息数据');
            }
            break;
          case 5: // 新消息
            if (message.receivemessage === this.username && this.selectedFriend === message.sendmessage) {
              this.messages.push({ text: message.content, isUser: false });
              console.log('收到新消息:', message.content);
            }
            break;
          default:
            console.log('收到未知类型的消息:', message.type);
        }
      } catch (error) {
        console.error('处理消息失败:', error);
      }
    },
    goBack() {
      window.history.back();
    }
  },
  beforeDestroy() {
    if (this.ws) {
      console.log('关闭WebSocket连接...');
      this.ws.close();
    }
  }
};
</script>

<style scoped>
.chat-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
  font-family: Arial, sans-serif;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.back-button {
  padding: 5px 10px;
  background-color: #f1f1f1;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.back-button:hover {
  background-color: #ddd;
}

.username {
  font-weight: bold;
  color: #333;
}

.chat-main {
  display: flex;
  height: 600px;
}

.friend-list {
  width: 200px;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 10px;
  margin-right: 20px;
  background-color: #f9f9f9;
}

.friend-list h3 {
  margin-top: 0;
  margin-bottom: 10px;
  padding-bottom: 5px;
  border-bottom: 1px solid #ddd;
}

.friend-list ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.friend-list li {
  padding: 8px 5px;
  cursor: pointer;
  border-radius: 3px;
}

.friend-list li:hover {
  background-color: #e9e9e9;
}

.chat-box {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.chat-content {
  flex: 1;
  border: 1px solid #ddd;
  border-radius: 5px;
  padding: 15px;
  overflow-y: auto;
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
}

.message {
  margin-bottom: 15px;
  display: flex;
}

.message-container {
  display: flex;
  width: 100%;
}

.user-message-container {
  justify-content: flex-end;
}

.other-message-container {
  justify-content: flex-start;
}

.message-bubble {
  padding: 10px;
  border-radius: 5px;
  word-break: break-word;
  max-width: 80%;
}

.user-message {
  background-color: #e1f5fe;
}

.other-message {
  background-color: #f1f1f1;
}

.divider-line {
  align-self: center;
  padding: 5px 0;
  color: #999;
  font-size: 12px;
  text-align: center;
  width: 100%;
  margin: 10px 0;
}

.chat-input {
  display: flex;
  margin-top: 10px;
}

.chat-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px 0 0 4px;
}

.chat-input button {
  padding: 10px 15px;
  background-color: #2196F3;
  color: white;
  border: none;
  border-radius: 0 4px 4px 0;
  cursor: pointer;
}

.select-friend-hint {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 600px;
  color: #666;
  font-size: 18px;
}
</style>